package main

import "fmt"

func main() {
	h := &ListNode{
		Val: 1,
		Next: &ListNode{
			Val: 2,
			// Next: &ListNode{
			// 	Val: 3,
			// 	Next: &ListNode{
			// 		Val: 4,
			// 		Next: &ListNode{
			// 			Val:  5,
			// 			Next: nil,
			// 		},
			// 	},
			// },
		},
	}

	p := removeNthFromEnd(h, 2)
	fmt.Println(p)
}

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func removeNthFromEnd(head *ListNode, n int) *ListNode {
	p1 := head
	p2 := head

	if head.Next == nil {
		return nil
	}

	if head.Next.Next == nil {
		if n == 2 {
			return head.Next
		} else if n == 1 {
			head.Next = nil
			return head
		}
	}

	for n >= 1 {
		p2 = p2.Next
		n--
	}

	if p2 == nil {
		return p1.Next
	}

	for p2.Next != nil {
		p2 = p2.Next
		p1 = p1.Next
	}

	if p1.Next != nil {
		p1.Next = p1.Next.Next
	}

	return head
}

type ListNode struct {
	Val  int
	Next *ListNode
}
